package com.yupi.springbootinit.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import com.yupi.springbootinit.common.UserContext;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author admin
 * @date 2025/4/24
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 判断是否是静态方法
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 测试jwt
        String token = request.getHeader("Token");
        if(StrUtil.isNotBlank(token)) {
            // 校验是否过期
            JWTValidator.of(token).validateDate(DateUtil.date());
            JWT jwt = JWT.of(token);
            Object userInfo = jwt.getPayload("userInfo");
            if(userInfo != null) {
                UserVO user = JSONUtil.toBean((JSONObject) userInfo, UserVO.class);
                log.info("user:{}", user);
            }
            log.info("jwt:{}", userInfo);
        }
        // 3. 存储信息
        Object obj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = null;
        if (obj != null) {
            user = (User) obj;
            UserContext.setUser(user);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
